<template>
  <div class="production-scheduling">
    <h1>生产排产</h1>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="80px" inline>
        <el-form-item label="工单编号">
          <el-input v-model="searchForm.productionOrderCode" placeholder="请输入工单编号" clearable />
        </el-form-item>
        <el-form-item label="工单名称">
          <el-input v-model="searchForm.productionOrderName" placeholder="请输入工单名称" clearable />
        </el-form-item>
        <el-form-item label="产品编号">
          <el-input v-model="searchForm.material.code" placeholder="请输入产品编号" clearable />
        </el-form-item>
        <el-form-item label="产品名称">
          <el-input v-model="searchForm.material.name" placeholder="请输入产品名称" clearable />
        </el-form-item>
        <el-form-item label="客户编号">
          <el-input v-model="searchForm.customer.code" placeholder="请输入客户编号" clearable />
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="searchForm.customer.name" placeholder="请输入客户名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 工单列表 -->
    <el-card class="table-card">
      <el-table
          :data="scheduledOrderList"
          border
          stripe
          row-key="id"
          :loading="tableLoading"
      >
        <el-table-column prop="productionOrderCode" label="工单编号" />
        <el-table-column prop="productionOrderName" label="工单名称" />
        <el-table-column prop="materialCode" label="产品编号" />
        <!-- 产品名称数据绑定 -->
        <el-table-column label="产品名称">
          <template #default="scope">
            {{ scope.row.material?.name || '--' }}
          </template>
        </el-table-column>
        <!-- 规格型号数据绑定 -->
        <el-table-column label="规格型号">
          <template #default="scope">
            {{ scope.row.material?.specification || '--' }}
          </template>
        </el-table-column>
        <!-- 单位数据绑定 -->
        <el-table-column label="单位">
          <template #default="scope">
            {{ scope.row.material?.unit?.name || '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="productionOrderQuantity" label="工单数量" />
        <el-table-column label="已生产数量" align="center">
          <template #default="scope">
            {{ scope.row.producedQty || 0 }}  <!-- 无数据时显示0 -->
          </template>
        </el-table-column>
        <el-table-column prop="customerCode" label="客户编号" />npm
        <el-table-column prop="customerName" label="客户名称" />
        <el-table-column prop="requestDate" label="需求日期" />
        <el-table-column label="状态">
          <template #default="scope">
            <el-tag :type="getStatusTagType(getStatusValue(scope.row))">
              {{ scope.row.statusDictData?.dictLabel || '--' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleDetail(scope.row)">详情</el-button>
            <el-button @click="handleProschedule(scope.row)">排产</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页栏 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 详情弹窗 -->
    <el-dialog
        title="工单详情"
        v-model="detailDialogVisable"
        width="80%"
        :close-on-click-modal="false"
    >
      <el-descriptions :column="3" border>
        <el-descriptions-item label="工单编号">{{ detailForm.productionOrderCode }}</el-descriptions-item>
        <el-descriptions-item label="工单名称">{{ detailForm.productionOrderName }}</el-descriptions-item>
        <el-descriptions-item label="工单类型">
          {{ getDictLabel(productionOrderTypeDictDataList, detailForm.productionOrderType) }}
        </el-descriptions-item>
        <el-descriptions-item label="工单来源">{{ detailForm.productionOrderSource === 1 ? '客户订单' : '库存备货' }}</el-descriptions-item>
        <el-descriptions-item label="订单编号">{{ detailForm.orderCode || '-' }}</el-descriptions-item>
        <el-descriptions-item label="工单状态">
          <el-tag :type="getStatusTagType(getStatusValue(detailForm))">
            {{ detailForm.statusDictData?.dictLabel || '--' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="物料编号">{{ detailForm.materialCode }}</el-descriptions-item>
        <el-descriptions-item label="物料名称">{{ detailForm.material?.name || '-' }}</el-descriptions-item>
        <el-descriptions-item label="规格型号">{{ detailForm.material?.specification || '-' }}</el-descriptions-item>
        <el-descriptions-item label="计量单位">{{ detailForm.material?.unit?.name || '-' }}</el-descriptions-item>
        <el-descriptions-item label="工单数量">{{ detailForm.productionOrderQuantity }}</el-descriptions-item>
        <el-descriptions-item label="已生产数量">{{ detailForm.producedQuantity || 0 }}</el-descriptions-item>
        <el-descriptions-item label="客户编号">{{ detailForm.customerCode || '-' }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ detailForm.customerName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="需求日期">{{ detailForm.requestDate }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{ detailForm.creatorName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailForm.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailForm.updateTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="3">{{ detailForm.remark || '-' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisable = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>

  <!-- 排产弹窗 -->
  <el-dialog v-model="proscheduleDialogVisabel" title="生产排产" width="80%">
    <template #header>生产排产</template>
    <template #default>
      <div style="height: 450px;border: 1px solid #ccc; border-radius: 10px">
        <el-form :model="scheduleForm" label-width="120px" class="form-layout">
          <el-form-item label="工单编号">
            <el-input v-model="scheduleForm.productionOrderCode" readonly />
          </el-form-item>
          <el-form-item label="工单名称">
            <el-input v-model="scheduleForm.productionOrderName" readonly />
          </el-form-item>
          <el-form-item label="工单来源">
            <el-radio-group v-model="scheduleForm.productionOrderSource" disabled>
              <el-radio :label="1">客户订单</el-radio>
              <el-radio :label="2">库存备货</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="订单编号" v-if="scheduleForm.productionOrderSource === 1">
            <el-input v-model="scheduleForm.orderCode" readonly />
          </el-form-item>
          <el-form-item label="工单类型">
            <el-select v-model="scheduleForm.productionOrderType" style="width: 100%" disabled>
              <el-option
                  v-for="dictData in productionOrderTypeDictDataList"
                  :value="dictData.id"
                  :label="dictData.dictLabel"
                  :key="dictData.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="产品编号">
            <el-input v-model="scheduleForm.materialCode" readonly />
          </el-form-item>
          <el-form-item label="产品名称">
            <el-input v-model="scheduleForm.material.name" readonly />
          </el-form-item>
          <el-form-item label="规格型号">
            <el-input v-model="scheduleForm.material.specification" readonly />
          </el-form-item>
          <el-form-item label="计量单位">
            <el-input v-model="scheduleForm.material.unit.name" readonly />
          </el-form-item>
          <el-form-item label="工单数量">
            <el-input-number v-model="scheduleForm.productionOrderQuantity" :min="1" disabled />
          </el-form-item>
          <el-form-item label="需求日期">
            <el-date-picker v-model="scheduleForm.requestDate" type="date" value-format="YYYY-MM-DD" disabled />
          </el-form-item>
          <el-form-item label="客户编号" v-if="scheduleForm.productionOrderSource === 1">
            <el-input v-model="scheduleForm.customerCode" readonly />
          </el-form-item>
          <el-form-item label="客户名称" v-if="scheduleForm.productionOrderSource === 1">
            <el-input v-model="scheduleForm.customerName" readonly />
          </el-form-item>
          <el-form-item label="排产状态">
            <el-input v-model="scheduleForm.scheduleStatus" readonly />
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" v-model="scheduleForm.remark" rows="3" readonly />
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-tabs type="border-card" @tab-click="handleWorkflowTabClick">
          <el-tab-pane
              v-for="workflow in workflowList"
              :name="workflow.id"
              :label="workflow.workflowName">
            <el-tabs @tab-click="handleProcessTabClick">
              <el-tab-pane
                  v-for="process in workflow.processes"
                  :label="process.processName"
                  :name="process.id"
              >
                <el-row>
                  <el-button-group>
                    <el-button>新增</el-button>
                    <el-button>修改</el-button>
                    <el-button>删除</el-button>
                  </el-button-group>
                </el-row>
                <el-row>
                  任务列表
                  <el-table
                      :data="process.taskList"
                  >
                    <el-table-column prop="id" label="#"/>
                    <el-table-column prop="name" label="#"/>
                  </el-table>
                </el-row>
              </el-tab-pane>
            </el-tabs>
          </el-tab-pane>
        </el-tabs>
      </div>
    </template>
    <template #footer>
      <el-button @click="proscheduleDialogVisabel = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
  getProductionOrderList,
  getProductionOrderTypeDictData,
  getProductionOrderStatusDictData
} from "@/api/production-order.js";
import {getWorkflowByMaterialCode} from "@/api/workflow.js";

// 响应式数据
const searchForm = ref({
  productionOrderCode: "",
  productionOrderName: "",
  material: {
    code: "",
    name: ""
  },
  customer: {
    code: "",
    name: ""
  },
});
const scheduledOrderList = ref([]);
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
});
const tableLoading = ref(false);
const detailDialogVisable = ref(false);
const detailForm = ref({});

const scheduleForm = ref({
  scheduleStatus: "已确认" // 排产状态默认已确认
});

// 字典数据
const productionOrderTypeDictDataList = ref([]);
const productionOrderStatusDictDataList = ref([]);

const proscheduleDialogVisabel = ref(false);

const productionOrder=ref({
  materialCode:'MAT001', // 暂时写死
})

// 商品的工艺列表
const workflowList = ref([]);

// 当前选中的工艺编号
const currentWorkflowId = ref(undefined);

// 工具函数：获取状态值
const getStatusValue = (row) => {
  // 优先从statusDictData.dictValue获取，没有则从status获取
  let value = row.statusDictData?.dictValue ?? row.status;
  // 转换为数字
  return Number(value) || 0;
};

// 工具函数：获取状态标签类型
const getStatusTagType = (statusValue) => {
  switch (Number(statusValue)) {
    case 1:
      return "info"; // 草稿
    case 2:
      return "warning"; // 待审核
    case 3:
      return "success"; // 已审核
    case 4:
      return "danger"; // 已取消
    default:
      return "default";
  }
};

// 安全的字典标签获取函数
const getDictLabel = (dictList, value) => {
  if (!value) return "--";
  const safeDictList = Array.isArray(dictList) ? dictList : [];
  const matched = safeDictList.find(item => item.id === value);
  return matched ? matched.dictLabel : value;
};

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    productionOrderCode: "",
    productionOrderName: "",
    material: {
      code: "",
      name: ""
    },
    customer: {
      code: "",
      name: ""
    },
  };
  pagination.value.currentPage = 1;
  handleSearch();
};

// 搜索工单列表（筛选已审核通过的工单）
const handleSearch = () => {
  tableLoading.value = true;
  // 构建查询参数，与工单列表页面保持一致
  const params = {
    productionOrderCode: searchForm.value.productionOrderCode,
    productionOrderName: searchForm.value.productionOrderName,
    materialCode: searchForm.value.material.code,
    materialName: searchForm.value.material.name,
    customerCode: searchForm.value.customer.code,
    customerName: searchForm.value.customer.name,
    pageNum: pagination.value.currentPage,
    pageSize: pagination.value.pageSize,
    status: 3 // 筛选已审核通过的工单
  };

  getProductionOrderList(params).then(res => {
    tableLoading.value = false;
    if (res.code === 200) {
      scheduledOrderList.value = Array.isArray(res.data.list) ? res.data.list : [];
      pagination.value.total = res.data.total || 0;
    } else {
      ElMessage.error(res.msg || "工单列表加载失败");
      scheduledOrderList.value = [];
      pagination.value.total = 0;
    }
  }).catch(err => {
    tableLoading.value = false;
    console.error('工单列表接口错误：', err);
    ElMessage.error("工单列表加载异常");
  });
};

// 分页事件
const handleSizeChange = (pageSize) => {
  pagination.value.pageSize = pageSize;
  handleSearch();
};

const handleCurrentChange = (newPage) => {
  pagination.value.currentPage = newPage;
  handleSearch();
};

// 详情弹窗
const handleDetail = (row) => {
  detailForm.value = JSON.parse(JSON.stringify(row));
  detailDialogVisable.value = true;
};

// 字典加载
const loadProductionOrderTypeDictDataList = () => {
  getProductionOrderTypeDictData().then(res => {
    if (res.code === 200) {
      productionOrderTypeDictDataList.value = res.data || [];
    } else {
      ElMessage.error("工单类型字典加载失败: " + (res.msg || ''));
      productionOrderTypeDictDataList.value = [];
    }
  }).catch(err => {
    console.error('工单类型字典接口错误：', err);
    ElMessage.error("工单类型字典加载异常");
    productionOrderTypeDictDataList.value = [];
  });
};

const loadProductionOrderStatusDictDataList = () => {
  getProductionOrderStatusDictData().then(res => {
    if (res.code === 200) {
      productionOrderStatusDictDataList.value = res.data || [];
    } else {
      ElMessage.error("工单状态字典加载失败: " + (res.msg || ''));
      productionOrderStatusDictDataList.value = [];
    }
  }).catch(err => {
    console.error('工单状态字典接口错误：', err);
    ElMessage.error("工单状态字典加载异常");
    productionOrderStatusDictDataList.value = [];
  });
};

// 页面初始化
onMounted(() => {
  loadProductionOrderTypeDictDataList();
  loadProductionOrderStatusDictDataList();
  handleSearch();
});

const handleProschedule = (row) => {
  // 赋值工单数据到排产表单
  scheduleForm.value = {
    ...row,
    scheduleStatus: "已确认" // 设置默认排产状态
  };
  // 加载工艺列表
  getWorkflowByMaterialCode(row.materialCode)
      .then(res => {
        workflowList.value = res.data;
        proscheduleDialogVisabel.value = true; // 数据加载完成后显示弹窗
      })
};

// 工艺选项卡选中事件
const handleWorkflowTabClick = (panel)=>{
  // 记录当前选中的工艺
  currentWorkflowId.value = panel.props.name;
}
// 工序的tab选中触发的事件
const handleProcessTabClick = (panel)=>{
  console.log(panel)
  console.log(panel.props.name);// 工序的编号
  // 查询任务列表
  
  // 工具工序编号找到工序
  workflowList.value.forEach(workflow=>{
    if(workflow.id == currentWorkflowId.value){
      // 这个工艺就是当前选中的工艺
      workflow.processes.forEach(process=>{
        if(process.id == panel.props.name){
          // 找到当前工序
          // 查询当前工单中，当前工艺，当前工序的任务列表
          let tasks = [
            {id:"id" + panel.props.name ,name:panel.props.label},
            {id:"id" + panel.props.name ,name:panel.props.label},
            {id:"id" + panel.props.name ,name:panel.props.label},
            {id:"id" + panel.props.name ,name:panel.props.label}
          ]
          // 将查询的任务列表设置到process的taskList中
          process.taskList = tasks;
        }
      });
    }
  })
}
</script>

<style scoped>
.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
.form-layout {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}
.form-layout .el-form-item {
  margin-bottom: 0;
}

.el-descriptions-item {
  word-break: break-all;
}
</style>
